#!/usr/bin/env perl
use warnings;
use strict;

use CGI;
use DBI;
use Digest::SHA qw(sha1_hex);
use URI::Escape qw(uri_escape);

# change /path/to/includes to match your setup
BEGIN { use constant INCLUDES => '/path/to/includes'; }
BEGIN { require(INCLUDES . '/functions.pl'); }
BEGIN { require(INCLUDES . '/database.pl'); }
BEGIN { require(INCLUDES . '/images.pl'); }

my $ua = USERAGENT;
my $modify = HBW_MODIFY;
my $site = LBW_IMG_DIR;
my $curl = CURL;

# create database connection
my $dbh = DBI->connect(DB_DBI, DB_USER, DB_PASS);

# get cookie data
my $cgi = CGI->new;
my $user_hash = $cgi->cookie('user');

# fetch user credentials
my %user = get_user($dbh, $user_hash);

# check user credentials
if ($user{'hash'} ne $user_hash) {
    $dbh->disconnect;
    error BAD_CREDS;
} elsif (not ($user{'permissions'} & ACCESS_IMG_UP)) {
    $dbh->disconnect;
    error ACCESS_DENIED;
}

# fetch cgi parameters
my ($id, $action);
$id = int($cgi->param('image')) if (defined($cgi->param('image')));
$action = $cgi->param('action') if (defined($cgi->param('action')));

if (not (defined($id) and defined($action))) {
    $dbh->disconnect;
    error BAD_CGI;
}

# get image information
my ($hash, $name, $filename, $thumb) = get_image_data($dbh, $id);
if (not (defined($hash))) {
    $dbh->disconnect;
    error BAD_CGI;
}

# generate secret hash
my $hash2 = sha1_hex($hash . SEED);

# perform correct action
if ($action eq 'delete') {
    my $safe_filename = uri_escape($filename);
    my @response = `$curl -s -A "$ua" -d action=delete -d hash=$hash -d hash2=$hash2 -d image=$safe_filename $modify`;
    my $status = parse_response(@response);

    if ($status eq 'okay') {
        my $sth = $dbh->prepare("DELETE FROM images WHERE id = ?");
        $sth->execute($id);
        $sth->finish;
    }
} elsif ($action eq 'make_thumbnail') {
    my $safe_filename = uri_escape($filename);
    my @response = `$curl -s -A "$ua" -d action=make_thumbnail -d hash=$hash -d hash2=$hash2 -d image=$safe_filename $modify`;
    my $status = parse_response(@response);

    if ($status eq 'okay') {
        my $thumbnail = get_thumbname($filename);
        my $sth = $dbh->prepare("UPDATE images SET thumbnail = ? WHERE id = ?");
        $sth->execute($thumbnail, $id);
        $sth->finish;
    }
} elsif ($action eq 'rename') {
    # TODO: implement
} else {
    $dbh->disconnect;
    error BAD_CGI;
}

# print the redirect
print <<END;
Status: 302 Found
Location: $site/
Content-Type: text/html

END

$dbh->disconnect;
